<template>
  <div class="design-connect">
    <!-- :data="concernDatas.tabelData" -->
    <je-table
      ref="xTable"
      auto-resize
      show-overflow="ellipsis"
      keep-source
      show-header-overflow
      :store="concernStore"
      resizable
      size="small"
      header-align="center"
      :scroll-y="{ mode: 'wheel' }"
      :edit-config="{
        trigger: 'click',
        mode: 'cell',
        showUpdateStatus: true,
        showInsertStatus: false,
      }"
    >
      <!-- showUpdateStatus: true,
        showInsertStatus: false, -->
      <je-column title="操作" width="40" align="center">
        <template #header>
          <i style="font-size: 16px; cursor: pointer" class="fal fa-plus" @click="addColumn"></i>
        </template>
        <template #default="{ row }">
          <i
            style="font-size: 16px; cursor: pointer"
            class="fal fa-times"
            @click="deleteColumn(row)"
          ></i>
        </template>
      </je-column>
      <je-column field="mainTableCode" title="表A" :edit-render="{}">
        <template #edit="{ row }">
          <je-select
            v-model:value="row.mainTableCode"
            style="width: 100%"
            @select="selectTable1(row)"
          >
            <je-select-option
              v-for="item in tableDesigndata.selectDatas"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </je-select-option>
          </je-select>
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.mainTableCode, tableDesigndata.selectDatas) }}
        </template>
      </je-column>
      <je-column field="mainColumn" title="字段A" :edit-render="inputRender">
        <template #edit="{ row }">
          <je-grid-select
            v-model:value="row.mainColumn"
            :select-options="{ title: '选择字段' }"
            name="mainColumn"
            config-info="JE_CORE_TABLECOLUMN,mainColumn,TABLECOLUMN_CODE,S"
            :querys="getJQuery(row, 'mainTableCode')"
            :orders="[
              { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
              { code: 'SY_ORDERINDEX', type: 'ASC' },
            ]"
          />
        </template>
      </je-column>
      <je-column field="mainIdentifier" :edit-render="{}" width="100" align="center">
        <template #header>
          <i class="conditionicon fas fa-question-circle" @click="clickIcon('mainIdentifier')"></i>
          <!-- {{ $t('viewModal.designView.identifierACloumn') }} -->标识A
        </template>
        <template #edit="{ row }">
          <je-select
            v-model:value="row.mainIdentifier"
            style="width: 100%"
            @change="changeCheckbox(row)"
          >
            <je-select-option
              v-for="item in tableDesigndata.markingOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </je-select-option>
          </je-select>
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.mainIdentifier, tableDesigndata.markingOptions) }}
        </template>
      </je-column>
      <je-column field="formula" title="操作符" :edit-render="{}" width="150">
        <template #edit="{ row }">
          <je-select v-model:value="row.formula" style="width: 100%">
            <je-select-option
              v-for="item in tableDesigndata.connOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </je-select-option>
          </je-select>
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.formula, tableDesigndata.connOptions) }}
        </template>
      </je-column>
      <je-column field="targetTableCode" title="表B" :edit-render="{}">
        <template #edit="{ row }">
          <je-select
            v-model:value="row.targetTableCode"
            style="width: 100%"
            @select="selectTable2(row)"
          >
            <je-select-option
              v-for="item in tableDesigndata.selectDatas"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </je-select-option>
          </je-select>
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.targetTableCode, tableDesigndata.selectDatas) }}
        </template>
      </je-column>
      <je-column field="targetColumn" title="字段B" :edit-render="inputRender">
        <template #edit="{ row }">
          <je-grid-select
            v-model:value="row.targetColumn"
            name="targetColumn"
            config-info="JE_CORE_TABLECOLUMN,targetColumn,TABLECOLUMN_CODE,S"
            :querys="getJQuery(row, 'targetTableCode')"
            :orders="[
              { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
              { code: 'SY_ORDERINDEX', type: 'ASC' },
            ]"
          />
        </template>
      </je-column>
      <je-column field="targetIdentifier" :edit-render="{}" width="100" align="center">
        <template #header>
          <i
            class="conditionicon fas fa-question-circle"
            @click="clickIcon('targetIdentifier')"
          ></i>
          <!-- {{ $t('viewModal.designView.identifierBCloumn') }} -->标识B
        </template>
        <template #edit="{ row }">
          <je-select
            v-model:value="row.targetIdentifier"
            style="width: 100%"
            @change="changeCheckbox(row)"
          >
            <je-select-option
              v-for="item in tableDesigndata.markingOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </je-select-option>
          </je-select>
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.targetIdentifier, tableDesigndata.markingOptions) }}
        </template>
      </je-column>
      <je-column field="isDispalyLine" width="80" align="center">
        <template #header>
          <i class="conditionicon fas fa-question-circle" @click="clickIcon('isDispalyLine')"></i>
          <!-- {{ $t('viewModal.designView.showCloumn') }} -->显示
        </template>
        <template #default="{ row }">
          <je-checkbox
            v-model:checked="row.isDispalyLine"
            :disabled="row.disabled"
            @change="changeCheckbox(row)"
          />
        </template>
      </je-column>
      <!-- <template #tbar>
        <div class="design-title bottom"> {{ $t('viewModal.designView.titleDesign') }} </div>
      </template> -->
    </je-table>
  </div>

  <je-modal
    v-model:visible="visibleCondition"
    width="400px"
    title="说明"
    height="auto"
    :resize="false"
    ok-button
    button-align="right"
    :maximizable="false"
  >
    <div>
      {{ modalText }}
    </div>
  </je-modal>
</template>

<script>
  import { defineComponent, ref, onMounted, watch, reactive, nextTick } from 'vue';
  import { Grid, Data, Input, Select, Checkbox, InputSelect, Modal } from '@jecloud/ui';
  import { uuid, cloneDeep } from '@jecloud/utils';
  import { inputRender, numberRender } from '@/helper/edit-render';
  import { useSourceStore } from '@/store/source-store';
  export default defineComponent({
    name: 'DesignConnect',
    components: {
      JeTable: Grid,
      JeColumn: Grid.Column,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeCheckbox: Checkbox,
      JeGridSelect: InputSelect.Grid,
      JeModal: Modal,
    },
    props: {
      concernDatas: {
        type: Object,
        requied: true,
        default: () => {
          return {};
        },
      },
      tableId: {
        type: String,
        default: '',
      },
      addTable: {
        type: Object,
        default: () => {
          return {};
        },
      },
      deaignSelected: {
        type: Object,
        requied: true,
        default: () => {
          return {};
        },
      },
      deleteTableId: {
        type: String,
        default: '',
      },
    },
    emits: ['getConcernTable', 'changeLine'],
    setup(props, { emit }) {
      const sourceStore = useSourceStore(); //数据源全局状态
      const xTable = ref(null);

      onMounted(() => {
        nextTick(() => {
          emit('getConcernTable', getXTable());
        });
      });
      const state = reactive({
        //关联设计对应图表
        concernStore: Data.Store.useGridStore({
          data: [],
        }),
      });
      // setTimeout(() => {
      //   state.concernStore.loadData([...props.concernDatas.tabelData]);
      // }, 500);
      //加载数据
      const loadConcernData = (data) => {
        state.concernStore.loadData([...data]);
      };
      const tableDesigndata = reactive({
        selectDatas: props.concernDatas.selectDatas, //视图拖拽表的详细信息
        markingOptions: [
          { label: '1', value: '1' },
          { label: 'n', value: 'n' },
        ],
        connOptions: [
          { value: '=', label: '等于' },
          { value: '>', label: '大于' },
          { value: '<', label: '小于' },
          { value: '>=', label: '大于等于' },
          { value: '<=', label: '小于等于' },
          { value: '!=', label: '不等于' },
          { value: 'LEFT JOIN', label: '左连接' },
          { value: 'RIGHT JOIN', label: '右连接' },
          { value: 'JOIN', label: '笛卡儿积' },
        ],
      });

      //列表单元格格式化
      const getSelectLabel = (value, list, valueProp = 'value', labelField = 'label') => {
        const item = list.find((item) => item[valueProp] === value);
        return item ? item[labelField] : null;
      };

      //关系设置列表数据添加
      const addColumn = async () => {
        const $table = getXTable();
        const record = {
          id: uuid(),
          mainTableCode: '',
          mainColumn: '',
          mainIdentifier: '1',
          targetTableCode: '',
          targetColumn: '',
          targetIdentifier: '1',
          formula: '=',
          isDispalyLine: false,
          disabled: true,
          mainTableId: '',
          mainTableName: '',
          targetTableId: '',
          targetTableName: '',
        };
        state.concernStore.insert(record, -1);
        setConcernData(state.concernStore.data);
      };

      //关系设置列表数据删除
      const deleteColumn = (record) => {
        // const $table = getXTable();
        // $table.remove(record);
        state.concernStore.remove(record);
        record.isDispalyLine = false;
        emit('changeLine', record);
        getDisabled(record);
        setConcernData(state.concernStore.data);
      };

      //获得列表对象
      const getXTable = () => {
        return xTable.value.$plugin;
      };

      //列表复选框值改变改变连线
      const changeCheckbox = (row) => {
        emit('changeLine', row);
        getDisabled(row);
      };

      //表A值改变需要吧对应的id,name赋值
      const selectTable1 = (row) => {
        const tableCode = row.mainTableCode;
        tableDesigndata.selectDatas.forEach((item) => {
          if (item.value == tableCode) {
            row.mainTableId = item.tableId;
            row.mainTableName = item.tableName;
          }
        });
        getDisabled(row);
      };

      //表B值改变需要吧对应的id,name赋值
      const selectTable2 = (row) => {
        const tableCode = row.targetTableCode;
        tableDesigndata.selectDatas.forEach((item) => {
          if (item.value == tableCode) {
            row.targetTableId = item.tableId;
            row.targetTableName = item.tableName;
          }
        });
        getDisabled(row);
      };

      //判断显示列是否只读
      const getDisabled = (row) => {
        if (row.mainTableId == '' || row.targetTableId == '') {
          return false;
        }
        const tableData = getXTable().getTableData().tableData;
        let slectRow = [];
        //循环先找到选中的数据
        tableData.forEach((record) => {
          //如果A,B表一样
          if (row.mainTableId == row.targetTableId) {
            if (
              row.mainTableId == record.mainTableId &&
              row.targetTableId == record.targetTableId &&
              record.isDispalyLine
            ) {
              slectRow.push(record);
            }
          } else {
            if (
              (row.mainTableId == record.mainTableId || row.mainTableId == record.targetTableId) &&
              (row.targetTableId == record.targetTableId ||
                row.targetTableId == record.mainTableId) &&
              record.isDispalyLine
            ) {
              slectRow.push(record);
            }
          }
        });
        tableData.forEach((record) => {
          //如果A,B表一样
          if (row.mainTableId == row.targetTableId) {
            if (
              row.mainTableId == record.mainTableId &&
              row.targetTableId == record.targetTableId
            ) {
              //如果有选中的数据
              if (slectRow.length > 0) {
                //选中的数据和当前的数据是同一条就可以编辑
                if (slectRow[0].id == record.id) {
                  record.disabled = false;
                } else {
                  //选中的数据和当前的数据不是同一条不可以编辑
                  record.disabled = true;
                }
              } else {
                //没有选中的数据都可以编辑
                record.disabled = false;
              }
            }
          } else {
            if (
              (row.mainTableId == record.mainTableId || row.mainTableId == record.targetTableId) &&
              (row.targetTableId == record.targetTableId || row.targetTableId == record.mainTableId)
            ) {
              //如果有选中的数据
              if (slectRow.length > 0) {
                //选中的数据和当前的数据是同一条就可以编辑
                if (slectRow[0]._X_ID == record._X_ID) {
                  record.disabled = false;
                } else {
                  //选中的数据和当前的数据不是同一条不可以编辑
                  record.disabled = true;
                }
              } else {
                //没有选中的数据都可以编辑
                record.disabled = false;
              }
            }
          }
        });
      };

      //级联删除关系设置的Table数据
      const deleteTableData = (tableId) => {
        // const $table = getXTable();
        // $table.getTableData().tableData.forEach((item, index) => {
        //   if (item.mainTableId == tableId || item.targetTableId == tableId) {
        //     $table.remove(item);
        //     getDisabled(item);
        //   }
        // });
        state.concernStore.data.forEach((item) => {
          if (item.mainTableId == tableId || item.targetTableId == tableId) {
            state.concernStore.remove(item);
          }
        });
        setConcernData(state.concernStore.data);
      };

      //设置关联视图对应字段
      const setConcernData = (concernData) => {
        const curSourceCode = sourceStore.getSourceCode();
        const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
        curSourceData.DATASOURCE_INCIDENCE_RELATION = JSON.stringify(concernData);
      };

      //分装j_query
      const getJQuery = (row, tableCode) => {
        const j_query = [
          { code: 'TABLECOLUMN_TABLECODE', type: '=', value: row[tableCode], cn: 'and' },
          { code: 'TABLECOLUMN_ISCREATE', type: '=', value: '1', cn: 'and' },
        ];
        return j_query;
      };

      //点击icon
      const visibleCondition = ref(false);
      const modalText = ref('');
      const clickIcon = (type) => {
        visibleCondition.value = true;
        //标识A
        if (type == 'mainIdentifier') {
          modalText.value = '标识A表示表A与表B的数据映射关系。';
          //标识B
        } else if (type == 'targetIdentifier') {
          modalText.value = '标识B表示表B与表A的数据映射关系。';
          //显示
        } else if (type == 'isDispalyLine') {
          modalText.value = '勾选显示后，将在设计视图页面展示表A与表B的映射关系。';
        }
      };
      //重新加载数据
      const reloadRelevanData = () => {
        state.concernStore.loadData([...state.concernStore.data]);
      };
      //监听视图设计的变化
      watch(
        () => props.concernDatas.selectDatas,
        (val) => {
          tableDesigndata.selectDatas = val;
        },
        { deep: true },
      );
      //监听关联设计变化
      watch(
        () => props.concernDatas.tabelData,
        (val) => {
          const newCloumData = cloneDeep(val);
          state.concernStore.loadData(newCloumData);
        },
        { deep: true },
      );
      //监听设计视图的数据删除,级联删除数据
      watch(
        () => props.deleteTableId,
        (val) => {
          deleteTableData(val);
        },
        { deep: true },
      );
      //监听数据变化
      watch(
        () => state.concernStore.data,
        (val) => {
          setConcernData(val);
        },
        { deep: true },
      );

      return {
        tableDesigndata,
        getSelectLabel,
        addColumn,
        xTable,
        getXTable,
        deleteColumn,
        changeCheckbox,
        selectTable1,
        selectTable2,
        getDisabled,
        inputRender,
        numberRender,
        getJQuery,
        visibleCondition,
        clickIcon,
        modalText,
        reloadRelevanData,
        loadConcernData,
        ...state,
      };
    },
  });
</script>

<style lang="less" scoped>
  .design-title {
    height: 40px;
    background: #f7f9fc;
    line-height: 40px;
    font-size: 14px;
    padding: 0 16px;
    color: #3265f5;
  }
  .design-title.bottom {
    //position: relative;
    border-top: 1px solid #e6e6e6;
    border-bottom: 1px solid #e6e6e6;
  }
  .design-connect {
    width: 100%;
    height: 100%;
    .conditionicon {
      color: #ebebeb;
      cursor: pointer;
      margin-right: 5px;
      &:hover {
        color: #3265f5;
      }
    }
  }
</style>
